import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Copy, RefreshCw, Key } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import { Checkbox } from '@/components/ui/checkbox';

interface PasswordGeneratorWindowProps {
  isOpen: boolean;
  onClose: () => void;
}

const PasswordGeneratorWindow: React.FC<PasswordGeneratorWindowProps> = ({
  isOpen,
  onClose
}) => {
  const [password, setPassword] = useState('');
  const [length, setLength] = useState([16]);
  const [includeUppercase, setIncludeUppercase] = useState(true);
  const [includeLowercase, setIncludeLowercase] = useState(true);
  const [includeNumbers, setIncludeNumbers] = useState(true);
  const [includeSymbols, setIncludeSymbols] = useState(true);
  const [excludeSimilar, setExcludeSimilar] = useState(false);
  const [excludeAmbiguous, setExcludeAmbiguous] = useState(false);
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);

  // Generate initial password
  useEffect(() => {
    if (isOpen) {
      generatePassword();
    }
  }, [isOpen]);

  const generatePassword = () => {
    const charset = {
      uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
      lowercase: 'abcdefghijklmnopqrstuvwxyz',
      numbers: '0123456789',
      symbols: '!@#$%^&*()_+-=[]{}|;:,.<>?'
    };

    let availableChars = '';
    if (includeUppercase) availableChars += charset.uppercase;
    if (includeLowercase) availableChars += charset.lowercase;
    if (includeNumbers) availableChars += charset.numbers;
    if (includeSymbols) availableChars += charset.symbols;

    if (availableChars === '') {
      setPassword('');
      return;
    }

    // Remove similar characters if requested
    if (excludeSimilar) {
      availableChars = availableChars.replace(/[il1Lo0O]/g, '');
    }

    // Remove ambiguous characters if requested
    if (excludeAmbiguous) {
      availableChars = availableChars.replace(/[{}[\]()\/\\'"~,;.<>]/g, '');
    }

    let generatedPassword = '';
    for (let i = 0; i < length[0]; i++) {
      generatedPassword += availableChars.charAt(Math.floor(Math.random() * availableChars.length));
    }

    setPassword(generatedPassword);
  };

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(password);
      setToast({ message: '密码已复制到剪贴板', type: 'success' });
      setTimeout(() => setToast(null), 2000);
    } catch (error) {
      setToast({ message: '复制失败', type: 'error' });
      setTimeout(() => setToast(null), 2000);
    }
  };


  if (!isOpen) return null;

  return (
    <AnimatePresence>
      <motion.div
        initial={{ scale: 0.9, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.9, opacity: 0 }}
        transition={{ type: "spring", duration: 0.3 }}
        className="fixed bg-background border border-border rounded-lg shadow-xl w-full max-w-md cursor-move z-[9999]"
        style={{
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
        }}
        drag
        dragMomentum={false}
        dragConstraints={{
          top: -500,
          left: -500,
          right: 500,
          bottom: 500
        }}
      >
          {/* Header - Drag Handle */}
          <div 
            className="flex items-center justify-between p-4 border-b border-border cursor-move"
            style={{ cursor: 'move' }}
          >
            <div className="flex items-center gap-2">
              <Key className="w-5 h-5 text-primary" />
              <h2 className="text-lg font-semibold">密码生成器</h2>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={onClose}
              className="h-8 w-8 p-0 cursor-pointer"
            >
              <X className="w-4 h-4" />
            </Button>
          </div>

          {/* Content */}
          <div 
            className="p-4 space-y-6"
            style={{ cursor: 'default' }}
            onMouseDown={(e) => e.stopPropagation()}
          >
            {/* Generated Password */}
            <div className="space-y-2">
              <Label htmlFor="password">生成的密码</Label>
              <div className="flex gap-2">
                <Input
                  id="password"
                  value={password}
                  readOnly
                  className="font-mono text-sm"
                />
                <Button
                  variant="outline"
                  size="sm"
                  onClick={copyToClipboard}
                  className="px-3"
                >
                  <Copy className="w-4 h-4" />
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={generatePassword}
                  className="px-3"
                >
                  <RefreshCw className="w-4 h-4" />
                </Button>
              </div>
            </div>

            {/* Length Slider */}
            <div className="space-y-3">
              <Label>密码长度: {length[0]}</Label>
              <Slider
                value={length}
                onValueChange={setLength}
                max={64}
                min={4}
                step={1}
                className="w-full"
              />
            </div>

            {/* Character Options */}
            <div className="space-y-3">
              <Label>包含字符类型</Label>
              <div className="grid grid-cols-2 gap-3">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="uppercase"
                    checked={includeUppercase}
                    onCheckedChange={(checked) => setIncludeUppercase(checked as boolean)}
                  />
                  <Label htmlFor="uppercase" className="text-sm">大写字母 (A-Z)</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="lowercase"
                    checked={includeLowercase}
                    onCheckedChange={(checked) => setIncludeLowercase(checked as boolean)}
                  />
                  <Label htmlFor="lowercase" className="text-sm">小写字母 (a-z)</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="numbers"
                    checked={includeNumbers}
                    onCheckedChange={(checked) => setIncludeNumbers(checked as boolean)}
                  />
                  <Label htmlFor="numbers" className="text-sm">数字 (0-9)</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="symbols"
                    checked={includeSymbols}
                    onCheckedChange={(checked) => setIncludeSymbols(checked as boolean)}
                  />
                  <Label htmlFor="symbols" className="text-sm">符号 (!@#$...)</Label>
                </div>
              </div>
            </div>

            {/* Advanced Options */}
            <div className="space-y-3">
              <Label>高级选项</Label>
              <div className="space-y-2">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="excludeSimilar"
                    checked={excludeSimilar}
                    onCheckedChange={(checked) => setExcludeSimilar(checked as boolean)}
                  />
                  <Label htmlFor="excludeSimilar" className="text-sm">排除相似字符 (il1Lo0O)</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="excludeAmbiguous"
                    checked={excludeAmbiguous}
                    onCheckedChange={(checked) => setExcludeAmbiguous(checked as boolean)}
                  />
                  <Label htmlFor="excludeAmbiguous" className="text-sm">
                    排除模糊字符 ({' '} {'{'} {'}'} {'['} {']'} {'('} {')'} {'/'} {'\\'} {"'"} {'"'} {'~'} {','} {';'} {'.'} {'<'} {'>'} )
                  </Label>
                </div>
              </div>
            </div>

            {/* Action Buttons */}
            <div className="flex gap-2 pt-2">
              <Button
                onClick={generatePassword}
                className="flex-1"
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                重新生成
              </Button>
              <Button
                variant="outline"
                onClick={copyToClipboard}
                className="flex-1"
              >
                <Copy className="w-4 h-4 mr-2" />
                复制密码
              </Button>
            </div>
          </div>
        </motion.div>

        {/* Toast */}
        {toast && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 20 }}
            className={`fixed bottom-4 right-4 px-4 py-2 rounded-md shadow-lg z-[10000] ${
              toast.type === 'success' 
                ? 'bg-green-500 text-white' 
                : 'bg-red-500 text-white'
            }`}
          >
            {toast.message}
          </motion.div>
        )}
    </AnimatePresence>
  );
};

export default PasswordGeneratorWindow;
